﻿package component.tree.dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionProvider implements IConnectionProvider{
	
	public static String CONNECTION_CONFIG_FILE = "/connection.properties";
	
	private static Properties result;
	
	private Connection connection;
	
	//private Session session;
	
	//获取连接
	public Connection getConnection(){
		//方式1：
		this.connection = getConnByJdbc();
		
		//方式2：通过session获取connection
		
		return this.connection;
	}
	
	//关闭连接的资源
	public void close(ResultSet rs,PreparedStatement pstm){
		try{
			if(rs!=null){
				rs.close();
			}
			if(pstm!=null){
				pstm.close();
			}
			if(this.connection!=null){
				this.connection.close();
				this.connection = null;
			}
			
			//关闭session
			
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	
	//读取数据库连接的配置文件
	private Properties getProperties() {
		if(result != null) return result;
		
		result = new Properties();
		try {
			result.load(ConnectionProvider.class.getResourceAsStream(CONNECTION_CONFIG_FILE));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	
	//获取连接
	private Connection getConnByJdbc(){
		Properties result = getProperties();

		String className = result.getProperty("connection.driver_class");
		String url = result.getProperty("connection.url");
		String userName = result.getProperty("connection.username");
		String password = result.getProperty("connection.password");
		
		Driver driver = null;
		try {
			driver = (Driver) Class.forName(className).newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Connection connection = null;
		try {
			DriverManager.registerDriver(driver);
			connection = DriverManager.getConnection(url, userName, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return connection;
	}
	
	public static void main(String[] args) {
		IConnectionProvider provider = new ConnectionProvider();
		Connection c = provider.getConnection();
	}
}
